/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "Sphere.h"

namespace liba
{
namespace math
{

Sphere::Sphere( const Vector3<float> center, float radius )
:	center( center ),
	radius( radius )
{}

bool Sphere::intersect( const Sphere & sphere )const
{
	float radius_sum( get_radius() + sphere.get_radius() );
	return ( get_center() - sphere.get_center() ).length_2() <= radius_sum * radius_sum;
}

bool Sphere::contains( const Sphere & sphere )const
{
	float r( get_radius() - sphere.get_radius() );
	return r >= 0 ?	(get_center() - sphere.get_center()).length_2() <= r*r : false;
}

bool Sphere::contains( const Vector3<float> & point )const
{
	return ( point - get_center() ).length_2() <= get_radius() * get_radius();
}

void Sphere::merge( const Sphere & sphere )
{
	if( !sphere.contains(*this) )
	{
		Vector3<float> dir( sphere.get_center() - get_center() );
		float dir_length( dir.length() );
		float distance( dir_length + get_radius() + sphere.get_radius() );
		float center_offset( distance/2 - get_radius() );
		if( center_offset > 0 )
		{
			radius = distance/2;
			dir *= 1.0f / dir_length;
			center = get_center() + dir * center_offset;
		}
	}
	else
		*this = sphere;
}

} // namespace math
} // namespace liba

